
//  PublishLocationListController.m
//  Migrant
//
//  Created by aojun on 17/7/24.
//  Copyright © 2017年 chen. All rights reserved.
//所在位置

#import "MapLocationListController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <MAMapKit/MAMapKit.h>
#import "MCLocationManager.h"

#if BaseClass == 0
#import "UIViewController+Message.h"
#endif

@interface MapLocationListController ()<UITableViewDelegate,UITableViewDataSource,AMapSearchDelegate,MAMapViewDelegate,UISearchBarDelegate>
{
    BOOL _isUpaate;
}
@property (nonatomic,strong)UITableView *listTableView;

@property (nonatomic,strong)NSMutableArray *dataSourceArr;

@property(nonatomic,strong)AMapSearchAPI *mapSearch;

@property (nonatomic,strong)AMapPOIKeywordsSearchRequest *locationKeyWordReq;
@property (nonatomic,strong)AMapPOIAroundSearchRequest   *locationNearReq;
@property (nonatomic,strong)MAMapView *mapView;
@property (nonatomic,strong)AMapSearchAPI *search;
@property (nonatomic,strong)UISearchBar *searchBar;
@property (nonatomic,strong)UITableView *tableView;
 //在原有的大头针中添加自定义的修饰
@property (nonatomic, strong)MAPinAnnotationView *pointAnnotation;


@end

@implementation MapLocationListController


-(void)dealloc
{
    KDealloc(_listTableView)
    KDealloc(_dataSourceArr)
    KDealloc(_mapSearch)
    KDealloc(_locationKeyWordReq)
    KDealloc(_locationNearReq)
    KDealloc(_mapView)
    KDealloc(_search)
    KDealloc(_searchBar)
    KDealloc(_tableView)
    NSLog(@"释放了");
}
- (void)viewWillDisappear:(BOOL)animated {
    
    _mapView.showsUserLocation = NO;
    _mapView.delegate = nil;
    
    [super viewWillDisappear:animated];
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _isUpaate = NO;
    
    self.title = @"所在位置";
    
    MAMapView *map = ({
        MAMapView*l= [[MAMapView alloc] initWithFrame:CGRectMake(0,kFitH(44),kScreenW,kFitH(300))];
        l.delegate = self;
        //设置地图语言  默认是中文
        l.language = MAMapLanguageZhCN;
        //地图类型  默认是2D栅格地图
        l.mapType = MAMapTypeStandard;
        /// 打开定位 如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
        l.showsUserLocation = YES;
        //设置跟踪模式
        /*
         MAUserTrackingModeNone              = 0,    ///< 不追踪用户的location更新
         MAUserTrackingModeFollow            = 1,    ///< 追踪用户的location更新
         MAUserTrackingModeFollowWithHeading = 2     ///< 追踪用户的location与heading更新
         */
        l.userTrackingMode = MAUserTrackingModeFollow;

        ///设定定位精度。默认为kCLLocationAccuracyBest
        l.desiredAccuracy = kCLLocationAccuracyBest;
        /// 是否显示指南针
        l.showsCompass = NO;
        /// 设定定位的最小更新距离。默认为kCLDistanceFilterNone，会提示任何移动
        
        l.distanceFilter = 15.0f;
        /// 是否显示比例尺，默认为YES
        l.showsScale = NO;
        /// 是否支持缩放，默认为YES
        
        l.zoomEnabled = YES;
        /// 是否支持平移，默认为YES
        l.scrollEnabled = YES;
        /// 缩放级别, [3, 20]
        l.zoomLevel = 15;
        //                //开启定位
        //                l.showsUserLocation = YES;
        //                l.userInteractionEnabled = YES;
        //                //定位用户位置的模式
        //                l.userTrackingMode = MAUserTrackingModeFollow;
        //                //罗盘原点位置
        //                l.showsCompass = NO;
        //                //缩放级别, [3, 19],越高比例尺越小
        //                [l setZoomLevel:13.5];
        //                //比例尺原点位置
        //                l.scaleOrigin = CGPointMake(kScreenW - 160, 320);
        //                //地图跟着位置移动
        //                [l setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
        [self.view addSubview:l];
        l;
    });
    _mapView = map;
    
        //设置关键字检索参数
        AMapPOIKeywordsSearchRequest  *locationKeyWordReq = ({
                AMapPOIKeywordsSearchRequest*l=[[AMapPOIKeywordsSearchRequest alloc] init];
                l;
            });
            _locationKeyWordReq =locationKeyWordReq;
    //设置周边检索的参数
        AMapPOIAroundSearchRequest  *locationNearReq = ({
                AMapPOIAroundSearchRequest*l=[[AMapPOIAroundSearchRequest alloc] init];
                l;
            });
            _locationNearReq =locationNearReq;
    
   
    
       AMapSearchAPI  *mapSearch = ({
                AMapSearchAPI*l=[[AMapSearchAPI alloc] init];
                l.delegate = self;
                l;
            });
            _mapSearch =mapSearch;
    

  
    MCLocationManager *  location = [MCLocationManager sharedLocationManager];

    //获取定位
    WSELF(weakSelf);
    [location startUpdatingLocation:^(NSError *error, MCLocationInfo *locationInfo) {
        CLLocationCoordinate2D coordinate = locationInfo.lastLocation.coordinate;

        weakSelf.locationNearReq.location = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
        weakSelf.locationNearReq.offset = 30;
        weakSelf.locationNearReq.sortrule            = 0;
        weakSelf.locationNearReq.requireExtension    = YES;
        //[weakSelf.mapSearch AMapPOIAroundSearch:_locationReq];  //搜索关键词
        [weakSelf.mapSearch AMapPOIAroundSearch:weakSelf.locationNearReq];  //搜索周边
        
        //可以设置中心点的位置的
        weakSelf.mapView.centerCoordinate = coordinate;//weakSelf.mapView.userLocation.location.coordinate;

    }];

    
}

-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    if (_isUpaate != YES) {
        CGRect frame = self.view.frame;
        self.listTableView.frame = CGRectMake(0,self.mapView.bottom, frame.size.width, frame.size.height-self.mapView.bottom);
        self.searchBar.frame =CGRectMake(0,0,frame.size.width,kFitH(44));
        _isUpaate = YES;
    }

}


#pragma mark -----表格代理方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSourceArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"tradeCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }

    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    AMapPOI *model = self.dataSourceArr[indexPath.row];
    cell.textLabel.text = model.name;
    cell.textLabel.textColor = [UIColor blackColor];//hexCOLOR(@"");
    cell.detailTextLabel.text = model.address;
    cell.detailTextLabel.textColor = [UIColor lightGrayColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AMapPOI *model = self.dataSourceArr[indexPath.row];
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(model.location.latitude, model.location.longitude);
    self.pointAnnotation.annotation.coordinate = coordinate;
    //可以设置中心点的位置的
    self.mapView.centerCoordinate =coordinate;
    
    if (self.location) {
        self.location(model.location.latitude,model.location.longitude,[NSString stringWithFormat:@"%@%@%@%@",model.province,model.city,model.district,model.address]);
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}


-(void)onSelectLocation:(locationPosition)location
{
    if (self.location != location) {
        self.location = location;
    }
}


#pragma mark -----POI周边检索信息Delegate

- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    NSLog(@"查询结果");
    if (response.pois.count == 0)
    {
        [self showMessage:@"暂未相关位置信息"];
        
    }else
    {
        [self.dataSourceArr removeAllObjects];
        
        for(AMapPOI *p in response.pois){
            [self.dataSourceArr addObject:p];
        }
    }
    
    [self.listTableView reloadData];
}

- (void)searchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"====出错信息：%@",error);
}
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error{
    
    NSLog(@"====出错信息：%@",error);
}


/**
 *  设置POI搜素请求
 *
 *  @param keyword 搜索需要的关键字
 */
- (void)setPoiSearchMapWithKeyword:(NSString *)keyword{

    self.locationKeyWordReq.keywords = keyword;
    //搜索关键词
    [self.mapSearch AMapPOIKeywordsSearch:self.locationKeyWordReq];
    [self showMessage:@"开始搜索"];
}

#pragma mark -----MAMapView代理方法

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    //  if ([annotation isKindOfClass:[MAAnnotationView class]]) {
    static NSString *identify = @"annotation";
    //在原有的大头针中添加自定义的修饰
    MAPinAnnotationView *pointAnnotation = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identify];
    if (pointAnnotation == nil) {
        //在原有的大头针中创建一个新的自定义的大头针
        pointAnnotation = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identify];
    }
    //设置是否能选中的标题
    pointAnnotation.canShowCallout = YES;
    //是否允许拖拽
    pointAnnotation.draggable = YES;
    //是否允许退拽动画
    pointAnnotation.animatesDrop = YES;
    self.pointAnnotation = pointAnnotation;
    return pointAnnotation;
}






#pragma mark -----searchBar代理方法


- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}
/**
 *  设置左边的“取消”按钮
 *
 *  @param searchBar searchBar
 */
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    self.searchBar.showsCancelButton = YES;
    for (id cc in [searchBar.subviews[0] subviews]) {
        if ([cc isKindOfClass:[UIButton class]]) {
            UIButton * cancelButton = (UIButton *)cc;
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
}


// return NO to not resign first responder
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    return YES;
}

// called before text changes
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text NS_AVAILABLE_IOS(3_0){
    return YES;
}


/**
 *  键盘搜索按钮按下就会调用这个方法
 *
 *  @param searchBar searchBar本身
 */

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
      NSLog(@"关键词 text = %@",searchBar.text);
    //发起POI搜索请求
    [self setPoiSearchMapWithKeyword:searchBar.text];
    //收起键盘
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
    searchBar.text = @"";
}


/**
 *  “取消”按钮按下会调用这个方法
 *  收起键盘
 *  @param searchBar searchBar本身
 */
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    self.searchBar.showsCancelButton = NO;
}



-(UISearchBar *)searchBar
{
    if (!_searchBar) {
        UISearchBar *bar = ({
            UISearchBar*l= [[UISearchBar alloc] init];
            l.frame = CGRectZero;
            l.delegate = self;
            l.placeholder = @"请输入关键字";
            [self.view addSubview:l];
            l;
        });
        _searchBar =bar;
    }
    return _searchBar;
}




-(UITableView *)listTableView
{
    if (!_listTableView) {
        UITableView *tab = ({
            UITableView*l=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
            l.delegate =self;
            l.dataSource = self;
            l.tableFooterView = [[UIView alloc]init];
            
            [self.view addSubview:l];
            l;
        });
        _listTableView = tab;
    }
    return _listTableView;
}



- (NSMutableArray *)dataSourceArr{
    if (!_dataSourceArr) {
        _dataSourceArr = [[NSMutableArray alloc]init];
    }
    return _dataSourceArr;
}


@end
